<template>
	<view class="app-system-pay-order-info e-p-t-30 e-p-l-20 e-p-r-20" :style="[AppSkinVar]">
		<e-loading-page :loading="loading || payLoading">
			<template #icon>
				<loader></loader>
			</template>
		</e-loading-page>
		<order-header :info="orderStatus"></order-header>
		<view class="bg-white e-radius-20 overflow-hidd e-m-b-20">
			
			<view class="e-p-l-30 e-p-r-30 e-p-b-30 e-p-t-24">
				<logistics-card v-if="express" :express="express" :color="AppSkin.primary" @show="expressShow = true"></logistics-card>
				<view :class="[express ? 'app-system-pay-order-info__address e-rela e-p-l-46' : 'e-p-t-30']">
					<view class="e-m-b-10 e-flex">
						<view class="e-flex-1 e-m-r-40">
							<text class="fw-500">{{ $t('order.收货地址') }} : {{ info?.receivingAddress }}</text>
						</view>
						<view
							class="app-system-pay-order-info__address-btn c-primary e-font-24"
							@tap.stop="handleJumpAddress"
							v-if="!info?.updateAddressTime && info?.receivingStatus == 1"
						>
							{{ $t('order.更改') }}
						</view>
					</view>
					<view class="">
						<text class="c-secondary e-font-24 e-p-r-20">{{ $t('order.收货人') }} : {{ info?.receivingName }}</text>
						<text class="c-secondary e-font-24">{{ info?.receivingPhone }}</text>
					</view>
				</view>
			</view>
		</view>

		<store-address :info="info" v-if="info?.receivingType === 2"></store-address>
		<!-- <order-address :info="info" :showUpdateAddr="true"></order-address> -->

		<view class="bg-white e-flex e-flex-between e-p-30 e-m-b-20" v-if="info?.receivingType === 2">
			<text>{{ $t('nearby.自提时间') }}</text>
			<text class="fw-600">{{ todayText }}</text>
		</view>
		<view class="e-m-t-20">
			<order-goods-card :store="info?.store" :goodsList="info?.deputys" :isJump="true" :receivingStatus="info?.receivingStatus" :goodsLink="goodsLink">
				<template #button="{ goods, receivingStatus }">
					<goods-status :isDetail="true" @refund="applyRefund" :goods="goods" :receivingStatus="receivingStatus"></goods-status>
				</template>
				<template #deduction="{goods}" >
					<view v-if="goods.formJson" @tap.stop>
						<order-goods-form showReply :formJson="goods.formJson"  :price="goods.deputyMoney"
						:number="goods.commodityCount"></order-goods-form>
					</view>
					
				</template>
			</order-goods-card>
		</view>
		<view class="e-m-t-20 bg-white e-p-r-10 e-p-l-10 e-p-b-30 e-m-b-20" v-if="invoiceData">
			<view class="text-center c-333 e-font-30 e-p-30">
				电子普通发票
			</view>
			<e-line class="e-m-b-20"></e-line>
			<view class="e-flex e-p-20">
				<view class="e-flex-1 e-font-26" style="color: #808080;">
					发票类型
				</view>
				<view class="e-font-26 c-333">
					电子普通发票
				</view>
			</view>
			<view class="e-flex e-p-20">
				<view class="e-flex-1 e-font-26" style="color: #808080;">
					发票内容
				</view>
				<view class="e-font-26 c-333">
					商品明细
				</view>
			</view>
			<view class="e-flex e-p-20">
				<view class="e-flex-1 e-font-26" style="color: #808080;">
					抬头类型
				</view>
				<view class="e-font-26 c-333">
					{{invoiceData.billToType === 1 ? '个人' : '公司'}}
				</view>
			</view>
			<view class="e-flex e-p-20">
				<view class="e-flex-1 e-font-26" style="color: #808080;">
					抬头名称
				</view>
				<view class="e-font-26 c-333">
					{{invoiceData.billToName || ''}}
				</view>
			</view>
			<view class="e-flex e-p-20">
				<view class="e-flex-1 e-font-26" style="color: #808080;">
					开票金额
				</view>
				<view class="e-font-26 c-333">
					{{$unitEn}}{{invoiceData.price || ''}}
				</view>
			</view>
			<view class="e-flex e-p-20">
				<view class="e-flex-1 e-font-26" style="color: #808080;">
					申请时间
				</view>
				<view class="e-font-26 c-333">
					{{ timeFormat(invoiceData.createTime, 'yyyy-mm-dd') }}
				</view>
			</view>
			<view class="e-flex e-p-20" v-if="invoiceData.issueDate">
				<view class="e-flex-1 e-font-26" style="color: #808080;">
					开票时间
				</view>
				<view class="e-font-26 c-333">
					{{invoiceData.issueDate || ''}}
				</view>
			</view>
			
		</view>

		<order-code :info="info" v-if="info?.verifyCode"></order-code>
		<order-info :info="info || {}" @preview="previewOfflineInfo" :isDFK="isDFK"></order-info>
		<view class="e-p-t-20">
			<contact-view customClass="shadow-f3 bg-white e-p-24 e-flex-xy-center e-radius-20" :contact="false" @tapContact="handleTapContactIcon" v-if="SHOW_KEFU">
				<text class="iconfont icon-dingdanxiangqingkefuicon e-font-36 c-primary e-p-r-22"></text>
				<text class="e-font-30">{{ $t('order.联系卖家') }}</text>
			</contact-view>
		</view>
		
		<view class="order-button bg-white">
			<order-button
				v-if="info && !(info.receivingStatus === 0 && info.orderPayType === 'OFFLINE')"
				:info="info"
				:isDetail="true"
				@refund="applyRefund"
				@cancelRefund="cancelRefund"
				@cancel="cancelOrder"
				@deleteOrder="deleteOrder"
				@receiving="receiving"
				@pay="payShow = true"
			></order-button>
			<view class="ios-btm"></view>
		</view>
		
		<view style="height: 120rpx"></view>
		<refund-popup :type="popupType" :show="show" :color="AppSkin.primary" @close="show = false" @confirm="popupConfirm"></refund-popup>
		<pay-popup :storeType="info?.store?.type" :proIds="proIds" :payMoney="info?.orderMoneyPay" :show="payShow" @close="payShow = false" @pay="pay"></pay-popup>
		<e-popup :show="expressShow" mode="bottom" @close="expressShow = false">
			<view class="app-system-pay-order-info__popup">
				<view class="e-rela e-p-t-35 e-p-b-35 text-center">
					<text class="e-font-36 fw-500">{{ $t('order.物流跟踪') }}</text>
					<view class="app-system-pay-order-info__popup-close e-abso" @tap="expressShow = false">
						<app-image size="28rpx" src="order/close.png"></app-image>
					</view>
				</view>
				<scroll-view style="height: 80vh" scroll-y>
					<view class="bg-white">
						<view class="e-p-l-30 e-p-t-24 e-p-b-24 e-flex">
							<load-image mode="aspectFill" size="72rpx" shape="circle" :src="deliveryInfo.logo"></load-image>
							<view class="e-m-l-20">
								<text class="fw-600">{{ deliveryInfo.expName }} {{ deliveryInfo.number }}</text>
							</view>
						</view>
						<view class="app-system-pay-order-info__popup-list e-rela e-p-l-80 e-p-r-30 e-p-b-52">
							<view
								class="app-system-pay-order-info__popup-list__item e-rela"
								:class="[index === 0 ? 'c-da e-p-t-40' : 'e-p-t-60']"
								v-for="(item, index) in logisticList"
								:key="item.id"
							>
								<view class="e-m-b-12">
									<text :class="[index === 0 ? 'c-da' : 'c-secondary']">{{ $timeFormat(item.ftime, 'mm-dd hh:MM') }}</text>
								</view>
								<view>
									<text>{{ item.status }}</text>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</e-popup>
		<card-valid-code-popup :show="cardValidCodePopupShow" :payMoney="info?.orderMoneyPay" @cancel="handleCancelCardPay" @confirm="handleCardPay"></card-valid-code-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, watch, onUnmounted } from 'vue';
import { throttle, timeFormat, wxOpenBusinessView } from '@/common/utils';
import {
	getOrderDetail,
	postCancelOrder,
	postOrderReceiving,
	postApplyOrderRefund,
	postOrderRepayments,
	postCancelRefundOrder,
	getOfflineInfo,
	updateReceivingAddress,
	getPayResult,
	getExpressByOrder,
	getStoreUserThirdId,
	getInvoiceInfo
} from '@/common/request/api';
import type { AddressItem } from '@/common/request/api';
import orderHeader from '../child/order-header.vue';
import logisticsCard from '../child/logistics-card.vue';
import orderInfo from '../child/order-info.vue';
import orderButton from '../child/order-button.vue';
import refundPopup from '../child/refund-popup.vue';
import storeAddress from '../child/store-address.vue';
import goodsStatus from '../child/goods-status.vue';
import CardValidCodePopup from '../../child/cardValidCodePopup.vue'
import orderCode from '../child/order-code.vue';
import { useCurrentInstance, usePromise } from '@/common/hooks';
import { useI18n } from 'vue-i18n';
import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import { usePay } from '../../hooks/usePay';
import type { UniGlobalData } from '@/typings/uni';
import { PayType, SHOW_KEFU } from '@/env';
import { storeToRefs } from 'pinia';
import { useInit,useUser } from '@/common/stores';
const { AppSkin } = storeToRefs(useInit())
const ctx = useCurrentInstance();
const { t } = useI18n();

const { payLoading, systemPay,checkCardPay,handleCardPay,
		handleCancelCardPay,cardValidCodePopupShow, getH5PayResult } = usePay();
		
		const isDFK = ref(0)

	const {
		userInfo
	} = storeToRefs(useUser());

const loading = ref(false);
let orderId = '';
const invoiceData = ref()
// 查询发票详情
		const getInvoiceData = () => {
			getInvoiceInfo({orderId:info.value.orderId}).then(res => {
				if (res.code == 200) {
					invoiceData.value = res.data
					console.log(invoiceData.value,555)
				}
			})
		}

// 订单列表点击退款按钮时进入订单详情，showRefund变为true，显示退款弹窗后showRefund变为false
let showRefund = false;
// 订单列表点击付款按钮时进入订单详情，showPay变为true，显示付款弹窗后showPay变为false
let showPay = false;
// 订单列表点击取消订单按钮时进入订单详情，showCancel变为true，显示取消订单弹窗后showCancel变为false
let showCancel = false;

const orderStatus = ref<{
	title: string;
	subTitle?: string;
	icon?: string;
}>({
	title: '',
	icon: '1'
});
const orderStatusMap: Record<
	string,
	{
		title: string;
		subTitle?: string;
		icon?: string;
	}
> = {
	'0': {
		title: '等待买家付款',
		subTitle: '请尽快付款',
		icon: '1'
	},
	'1': {
		title: '买家已付款',
		icon: '2'
	},
	'2': {
		title: '卖家已发货',
		subTitle: '',
		icon: '3'
	},
	'3': {
		title: '交易成功',
		icon: '4'
	},
	'4': {
		title: '交易成功',
		icon: '4'
	},
	'5': {
		title: '交易关闭',
		icon: '5'
	},
	'6': {
		title: '申请退款中'
	},
	'7': {
		title: '已付款待审核',
		subTitle: '平台将会尽快审核',
		icon: '1'
	},
	'8': {
		title: '等待商家确认',
		icon: '1'
	},
	'10': {
		title: 'buyerNotPickUp',
		icon: '7'
	}
};

const todayText = ref('');

const [getOrderData, info] = usePromise(async () => {
	const res = await getOrderDetail(orderId);
	loading.value = false;
	if (res.data.receivingType === 2) {
		let date = new Date(res.data.predictTime!);
		let time = timeFormat(res.data.predictTime!, 'yyyy-mm-dd');
		let toDate = new Date();
		let day = date.getDay();
		let dayText = t(`nearby.周${'日一二三四五六'.charAt(day)}`);
		let toDay = time;
		if (time === timeFormat(toDate, 'yyyy-mm-dd')) {
			toDay = t('nearby.今天');
		} else {
			if (date.getFullYear() === toDate.getFullYear() && date.getMonth() === toDate.getMonth() && date.getDate() - toDate.getDate() === 1) {
				toDay = t('nearby.明日');
			}
		}

		todayText.value = `${toDay} (${dayText}) ${timeFormat(res.data.predictTime!, 'hh:MM')}`;
	}

	if (res.data.orderPayType === 'OFFLINE' && res.data.receivingStatus == 0) {
		orderStatus.value = orderStatusMap['7'];
	} else if (res.data.orderPayType === 'CASH' && res.data.receivingStatus == 0) {
		orderStatus.value = orderStatusMap['8'];
	} else if (res.data.receivingStatus === 10) {
		if (res.data.receivingType === 2) {
			orderStatus.value = {
				title: 'buyerNotPickUp',
				icon: '7'
			};
		} else {
			orderStatus.value = {
				title: '待使用',
				icon: '7'
			};
		}
	} else {
		orderStatus.value = orderStatusMap[`${res.data.receivingStatus}`];
	}

	if (showRefund && res.data.receivingStatus === 1 && res.data.orderRefundStatus === 0) {
		applyRefund();
		showRefund = false;
	}
	if (showPay && res.data.receivingStatus === 0) {
		payShow.value = true;
		showPay = false;
	}
	if (showCancel && res.data.receivingStatus === 0) {
		cancelOrder();
		showCancel = false;
	}
	return res.data;
});
const proIds = computed(() => {
	if(info.value) {
		getInvoiceData()
		return info.value.deputys.map((item) => item.commodityId).join(',');
	} else {
		return ''
	}
	
})

const deliveryInfo = ref({
	expName: '',
	number: '',
	logo: ''
});
const logisticList = ref<
	Array<{
		status: string;
		time: string;
	}>
>([]);
const expressShow = ref(false);
// 查询物流
const [getExpress, express] = usePromise(async () => {
	const res = await getExpressByOrder(info.value.orderId!);
	deliveryInfo.value = {
		expName: res.data?.travel?.expName || '',
		number: res.data?.travel?.number || '',
		logo: res.data?.travel?.logo || ''
	};
	logisticList.value = res.data?.travel?.list || [];
	return res.data?.travel?.list[0];
});

const getData = () => {
	getOrderData().then(() => {
		if (info.value.expressType === 1 && info.value.expressNumber) {
			getExpress();
		}
	});
};
const goodsLink = computed(() => (info.value?.store?.type === 2 ? '/pages/nearby/goods/index' : '/pages/classify/goods/info/index'));
const show = ref(false);
const popupType = ref(1);
const address = ref<AddressItem | null>(null);
const handleSelectAddress = (e: AddressItem) => {
	address.value = e;
};
const handleJumpAddress = () => {
	ctx.$goTo('/pages/user/receivingAddress/index', { type: 1 },{
		selectAddress:handleSelectAddress
	});
}
// 取消订单
const cancelOrder = throttle(function () {
	popupType.value = 1;
	show.value = true;
}, 1000);
// 申请退款
const applyRefund = (id?: string, goodsId?: string) => {
	if (info.value?.receivingStatus === 2) {
		ctx.$goTo(`/pages/order/refund/apply?id=${id}&goodsId=${goodsId}&orderId=${orderId}`);
	} else {
		popupType.value = 2;
		show.value = true;
	}
};
watch(address, (newValue) => {
	if (newValue && !info.value?.updateAddressTime) {
		console.log(newValue);
		uni.showLoading({
			title: 'loading...'
		});
		updateReceivingAddress({
			orderId: info.value.id!,
			addressId: newValue.id
		}).then((res) => {
			ctx.$toastApp(t('common.操作成功'));
			getData();
		});
	}
});
const payShow = ref(false);

//popup回调
const popupConfirm = (buyerMsg: string) => {
	show.value = false;
	if (popupType.value == 1) {
		postCancelOrder({
			orderId: info.value.orderId!
		}).then(() => {
			ctx.$goRedirectTo('/pages/order/success', {
				type: 0,
				id: orderId
			});
		});
	} else {
		postApplyOrderRefund(info.value.orderId!, {
			buyerMsg
		}).then(() => {
			ctx.$goRedirectTo('/pages/order/success', {
				type: 2,
				id: orderId
			});
		});
	}
};
// // 订单状态为发货后的申请退款
// const refund = () => {
// 	ctx.$goRedirectTo('/pages/order/success', {
// 		type: 2,
// 		id: orderId
// 	});
// };

// 订单取消退款
const cancelRefund = () => {
	postCancelRefundOrder(info.value.orderId!).then(() => {
		getData();
		ctx.$toastApp(t('common.操作成功'));
	});
};
// 删除订单
const deleteOrder = () => {
	uni.showToast({
		title: t('order.删除成功'),
		icon: 'success',
		duration: 2000,
		complete: () => {
			setTimeout(() => {
				ctx.$goRedirectTo('/pages/order/success', {
					type: 1,
					id: orderId
				});
			}, 1000);
		}
	});
};

const handleReceive = () => {
	postOrderReceiving({
		orderId: info.value.orderId!
	}).then(() => {
		ctx.$goRedirectTo('/pages/order/success', {
			type: 3,
			id: orderId
		});
	});
};
const handleReceiveTips = () => {
	ctx.$showModal({
		content: t('order.确认要收货吗'),
		success: (res) => {
			if (res.confirm) {
				handleReceive();
			}
		}
	});
};
// 确认收货
const receiving = () => {
	if (info.value?.orderPayType === 'WX' && info.value?.tranId) {
		wxOpenBusinessView({
			transaction_id: info.value.tranId
		})
			.then((e) => {
				console.log('success', e);
				if (e.status === 'success') {
					handleReceive();
				} else if (e.status === 'fail') {
					ctx.$toastApp(e.status);
				} else if (e.status === 'cancel') {
					console.log(e.extraData, 'e.extraData');
				}
			})
			.catch((res) => {
				if (res.code === 500) {
					ctx.$toastApp('确认失败，请重试');
				} else if (res.code === 401) {
					handleReceiveTips();
				}
			});
	} else {
		handleReceiveTips();
	}
};

const previewOfflineInfo = () => {
	getOfflineInfo(info.value!.payId).then((res) => {
		if (res.data.state === 0) {
			ctx.$goTo('/pages/offlinePay', {
				code: info.value!.payId
			});
		} else {
			uni.previewImage({
				urls: [ctx.$fullLink(res.data.voucherUrl)]
			});
		}
	});
};
// 立即付款
const pay = throttle(async function (payId: number, password: null | string = null, payType: PayType,payName:string, payisDefault:string,bankId?:number) {
	let data = {
		payId,
		fromType: getApp<UniGlobalData>().globalData?.payFromType,
		password,
		bankId
	};

	if(!bankId&&checkCardPay(payType,(cardId:number) => {
		pay(payId,payword, payType,payName,payisDefault,cardId)
	})){
		return 
	}
	uni.hideLoading();
	try {
		const res = await postOrderRepayments(info.value!.orderId, data);
		payLoading.value = false
		await systemPay({
			payType,
			resolveData: res,
			api: getPayResult,
			storageKey: 'payOrderId',
			payUrl: res.data,
			payParams: res.data,
			payMoney:info.value?.orderMoneyPay,
			successUrl: (id: string) => `order/success?type=4&id=${id}`,
			errorUrl: (msg: string) => `order/error?msg=${msg}`,
			orderUrl: 'order/index?type=1'
		});
	} catch (e) {
		ctx.$goTo(`/pages/order/error?msg=${e}`);
	}
}, 1500);
const handleTapContactIcon = () => {
	getStoreUserThirdId({
		userThirdId: info.value!.storeId
	}).then((res) => {
		ctx.$goTo('/pages/public/msg/detail', {
			oId: info.value!.deputys[0].deputyId,
			user: res.data.chatlinkid,
			bId: res.data.chat.bizid,
			sId: info.value!.storeId,
			name: info.value!.storeName,
			sT: info.value!.store.type
		});
	});
};


onLoad((opt) => {
	isDFK.value = opt.isDFK
	// transaction_id 用户点击微信的发货通知进入小程序后带的参数
	if (opt?.transaction_id) {
		orderId = opt.transaction_id;
	} else {
		orderId = opt!.id!;
	}
	if (opt?.refund) {
		showRefund = true;
	} else if (opt?.pay) {
		showPay = true;
	} else if (opt?.cancel) {
		showCancel = true;
	}
	// #ifdef HTML5 || PREVIEW
	getH5PayResult('order/success', 'payOrderId', getPayResult);
	// #endif
});

onShow(() => {
	getData();
});

onPullDownRefresh(() => {
	loading.value = true;
	getData().finally(() => {
		uni.stopPullDownRefresh();
	});
});

</script>

<style lang="scss">
	page{
		background: #F7F7F7;
	}
</style>

<style lang="scss" scoped>
@include appBem_b(system-pay-order-info) {
	@include appBem_e(address) {
		&::after {
			@include pseudoClass;
			width: 20rpx;
			height: 20rpx;
			border-radius: 100%;
			border: 2rpx solid var(--color-primary);
			background: $base-color-white;
			top: 8rpx;
			left: 0;
		}
		&-btn{
			border-radius: 100rpx;
			padding: 4rpx 20rpx;
			border: 2rpx solid var(--color-primary);
		}
	}
	@include appBem_e(popup) {
		background-color: #f7f7f7;
		&-close {
			top: 46rpx;
			right: 30rpx;
		}
		&-input {
			height: 100rpx;
			background: #f7f8fb;
			border-radius: 10rpx;
		}
		&-list {
			&::before {
				@include pseudoClass;
				width: 2rpx;
				height: calc(100% - 156rpx);
				background-color: #e6e6e6;
				top: 78rpx;
				left: 44rpx;
			}
			&__item {
				&::after {
					@include pseudoClass;
					width: 14rpx;
					height: 14rpx;
					background: #cccccc;
					border-radius: 100%;
					top: 72rpx;
					left: -42rpx;
					z-index: 2;
				}
				&:first-child {
					&::after {
						width: 24rpx;
						height: 24rpx;
						background: var(--color-primary);
						top: 60rpx;
						left: -46rpx;
					}
					&::before {
						@include pseudoClass;
						width: 32rpx;
						height: 32rpx;
						background-color: var(--color-primary);
						border-radius: 100%;
						z-index: 1;
						top: 54rpx;
						left: -50rpx;
						opacity: .2;
					}
				}
			}
		}
	}
}
.shadow-f3 {
	box-shadow: 0px -2rpx 0px 0px #f3f3f3;
}

.order-button {
	position: fixed;
	right: 0;
	bottom: 0;
	left: 0;
}

::v-deep {
	.goods-info2 {
		padding: 0 !important;
	}
}
</style>
